<template>
  <div class="profile-container">
    <!-- 第一屏：基本信息 -->
    <div class="first-screen">
      <el-row :gutter="30">
        <!-- 左侧个人信息 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="10">
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <el-icon><User /></el-icon>
                <span>个人信息</span>
              </div>
            </template>
            
            <el-form label-width="100px">
              <el-form-item label="姓名">
                <el-input v-model="form.name" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="form.email" />
              </el-form-item>
              <el-form-item label="加入的班级">
                <el-tag style="margin-right: 10px;" :type="index%2==0?'success':'warning'" v-for="(item,index) in form.gradeName">{{ item }} </el-tag>
              </el-form-item>
              <el-form-item label="余额">
                <el-tag type="info">{{ form.balance }} 元</el-tag>
                <el-button size="small" style="margin-left: 10px;" type="primary" @click="recharge">充值</el-button>
                <el-button size="small" style="margin-left: 10px;" type="warning" @click="updatePwd">修改密码</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 右侧数据统计 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="14">
          <el-row :gutter="20">
            <el-col :span="12">
              <StatCard
                title="今日刷题"
                :value="stats.todayQuestions"
                :icon="Notebook"
                color="#409EFF"
              />
            </el-col>
            <el-col :span="12">
              <StatCard
                title="本周刷题"
                :value="stats.weekQuestions"
                :icon="DataAnalysis"
                color="#67C23A"
              />
            </el-col>
            <el-col :span="12">
              <StatCard
                title="今日考试"
                :value="stats.todayExams"
                :icon="EditPen"
                color="#E6A23C"
              />
            </el-col>
            <el-col :span="12">
              <StatCard
                title="累计错题"
                :value="stats.totalWrong"
                :icon="Warning"
                color="#F56C6C"
              />
            </el-col>
            <el-col :span="12">
              <StatCard
                title="今日消费"
                :value="stats.todayConsumption"
                :icon="Coin"
                color="#e99d53"
              />
            </el-col>
            <el-col :span="12">
              <StatCard
                title="累计消费"
                :value="stats.totalConsumption"
                :icon="Money"
                color="#F56C6C"
              />
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <!-- 第二屏：图表分析 -->
    <div class="chart-section">
      <el-card>
        <template #header>
          <div class="chart-header">
            <el-icon><DataAnalysis /></el-icon>
            <span>学习数据统计</span>
          </div>
        </template>
        
        <VChart
          class="chart"
          :option="chartOption"
          :autoresize="true"
        />
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref,onMounted, h } from 'vue'
import { User, Notebook, EditPen, DataAnalysis, Warning,Coin,Money } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart } from 'echarts/charts'
import {
  GridComponent,
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import StatCard from '@/components/center/StatCard.vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { getUserInfoApi,userRechargeApi,updateUserPasswordApi } from '@/api/user'
import { getStudentSevenDaysLearnStatisticsApi } from '@/api/studentHome'



use([
  CanvasRenderer,
  BarChart,
  LineChart,
  GridComponent,
  TitleComponent,
  TooltipComponent,
  LegendComponent
])

// 表单数据
const form = ref({
  name: '',
  email: '',
  gradeName: [],
  balance: 0
})

/**
 * 加载用户个人信息
 */
const loadUserInfo = async() => {

  try {
    const { data,code } = await getUserInfoApi()
    console.log('个人中心',data)
    if(code===1){
      form.value.name = data.realName
      form.value.email = data.email
      // 逗号隔开的字符串转换成数组
      form.value.gradeName = data.gradeName?.split(',')

      // 余额保留两位小数
      form.value.balance = safeRound(data.balance || 0);
    } 
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }


}

/**
 * 处理数字保留两位小数
 * @param value 
 * @param decimals 
 */
const safeRound = (value:number, decimals = 2) => {
  const factor = Math.pow(10, decimals);
  return Math.trunc(value * factor) / factor;
}

// 统计信息
const stats = ref({
  // 今日刷题
  todayQuestions: 0,
  // 本周刷题
  weekQuestions: 0,
  // 今日考试
  todayExams: 0,
  // 累计错题
  totalWrong: 0,
  // 今日消费
  todayConsumption: 0,
  // 累计消费
  totalConsumption: 0
})


// 充值按钮点击事件
const recharge = async() => {
  try {
     // 先弹出金额输入框
     const result = await ElMessageBox.prompt('请输入充值金额', '充值', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d+(\.\d{1,2})?$/,  // 验证数字格式（支持两位小数）
      inputErrorMessage: '请输入有效的金额数字'
    })
    // 用户点击确定后继续执行
    const amount = parseFloat(result.value)
    if (isNaN(amount) || amount <= 0) {
      ElMessage.error('请输入有效的金额')
      return
    }
   const  {data,code} = await userRechargeApi(amount)
   if(code===1){
    const divForm = document.getElementById("alpayDiv");
      if (divForm)divForm.remove()
      const div = document.createElement("div");
      div.setAttribute("id", "alpayDiv");
      div.innerHTML = data ; // data就是接口返回的form 表单字符串
      document.body.appendChild(div);
      // 新开窗口跳转
      document.forms[1].setAttribute("target", "_blank");
      document.forms[1].submit();
   }
  } catch (error) {
    ElMessage.error('充值失败，请检查网络')
  }
  
}

// 修改密码按钮点击事件
const updatePwd = () => {
  // 修改密码 start
  let oldPassword = ''
  let newPassword = ''
  let confirmPassword = ''
  let errors = {
    old: '',
    new: '',
    confirm: ''
  }
  ElMessageBox({
    title: '修改密码',
    message: h('div', { class: 'password-form' }, [
      // 原始密码
      h('div', { class: 'form-item' }, [
        h('label', { class: 'form-label' }, '原始密码'),
        h('div', { class: 'form-content' }, [
          h('input', {
            type: 'password',
            class: 'el-input__inner' + (errors.old ? ' is-error' : ''),
            placeholder: '请输入当前使用的密码',
            onInput: (e) => {
              oldPassword = e.target.value
              errors.old = !oldPassword ? '必填字段' : ''
            }
          }),
          errors.old && h('div', { class: 'error-tip' }, errors.old)
        ])
      ]),

      // 新密码
      h('div', { class: 'form-item' }, [
        h('label', { class: 'form-label' }, '新密码'),
        h('div', { class: 'form-content' }, [
          h('input', {
            type: 'password',
            class: 'el-input__inner' + (errors.new ? ' is-error' : ''),
            placeholder: '6-20位字母/数字/下划线',
            onInput: (e) => {
              newPassword = e.target.value
              errors.new = !/^\w{6,20}$/.test(newPassword) ? '密码格式不符合要求' : ''
            }
          }),
          errors.new && h('div', { class: 'error-tip' }, errors.new)
        ])
      ]),

      // 确认密码
      h('div', { class: 'form-item' }, [
        h('label', { class: 'form-label' }, '确认密码'),
        h('div', { class: 'form-content' }, [
          h('input', {
            type: 'password',
            class: 'el-input__inner' + (errors.confirm ? ' is-error' : ''),
            placeholder: '请再次输入新密码',
            onInput: (e) => {
              confirmPassword = e.target.value
              errors.confirm = newPassword !== confirmPassword ? '两次输入密码不一致' : ''
            }
          }),
          errors.confirm && h('div', { class: 'error-tip' }, errors.confirm)
        ])
      ])
    ]),
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    showCancelButton: true,
    closeOnClickModal: false,
    dangerouslyUseHTMLString: true,
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        // 验证逻辑
        if (!oldPassword) {
          ElMessage.error('请输入原始密码')
          done(false)
          return
        }
        
        if (!/^\w{6,20}$/.test(newPassword)) {
          ElMessage.error('新密码需为6-20位字母、数字或下划线')
          done(false)
          return
        }

        if (newPassword !== confirmPassword) {
          ElMessage.error('两次输入的新密码不一致')
          done(false)
          return
        }

        // 所有验证通过
        instance.confirmButtonLoading = true
        try {
          // 这里可以添加调用修改密码API的逻辑
          const formData = {
            originPassword:oldPassword,
            checkedPassword:confirmPassword,
            newPassword:newPassword
          }
          const {code,msg} = await updateUserPasswordApi(formData)
          if(code===1){
            ElMessage.success(msg)
            done()
          }else{
            ElMessage.error(msg)
          }
          
        } catch (error) {
          ElMessage.error(error.message)
          done(false)
        } finally {
          instance.confirmButtonLoading = false
        }
      } else {
        done()
      }
    }
  })
  // 修改密码 end
}

// 图表配置
const chartOption = ref({
  title: {  
    text: '近七日学习数据',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['刷题数量', '考试次数'],
    top: 30
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '刷题数量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#409EFF'
      }
    },
    {
      name: '考试次数',
      type: 'line',
      data: [],
      smooth: true,
      itemStyle: {
        color: '#E6A23C'
      }
    }
  ]
})

/**
 * 获取近七天学习统计
 */
const getStudentSevenDaysLearnStatistics = async() => {
  try {
    const { data,code } = await getStudentSevenDaysLearnStatisticsApi()
    if(code===1){
      // 更新图表配置
      chartOption.value = {
        ...chartOption.value,
        xAxis: {
          ...chartOption.value.xAxis, // 保留xAxis其他配置（如type等）
          data: data.xaxis     // 仅更新数据
        },
        series: [
          {
            ...chartOption.value.series[0], // 保留原series[0]的所有配置
            data: data.exerciseData         // 仅更新数据
          },
          {
            ...chartOption.value.series[1], // 保留原series[1]的所有配置
            data: data.examData             // 仅更新数据
          }
        ]
      }
      
      stats.value = {
        todayQuestions: data.todayQuestions,
        weekQuestions: data.weekQuestions,
        todayExams: data.todayExams,
        totalWrong: data.totalWrong,
        todayConsumption: data.todayConsumption,
        totalConsumption: data.totalConsumption
      }

    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

onMounted(() => {
  loadUserInfo()
  getStudentSevenDaysLearnStatistics()
})
</script>

<style lang="scss" scoped>
.profile-container {


  .password-form {
  margin: 10px 0;
}
.input-item {
  margin: 15px 0;
}
.input-item label {
  display: block;
  margin-bottom: 5px;
  color: #606266;
}

  .first-screen {
    margin-bottom: 30px;
  }

  .info-card {
    margin-bottom: 20px;
    
    :deep(.el-card__header) {
      background-color: var(--el-color-primary-light-9);
    }
  }

  .chart-section {
    margin-top: 40px;

    .chart {
      height: 400px;
      width: 100%;
    }

    .chart-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 500;
    }
  }
}


.password-form {
  padding: 10px 5px;
}

.form-item {
  margin-bottom: 18px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.form-content {
  position: relative;
}

.el-input__inner {
  width: 100%;
  padding: 8px 15px;
  border-radius: 4px;
  transition: border-color 0.2s;
}

.el-input__inner.is-error {
  border-color: #f56c6c;
}

.error-tip {
  position: absolute;
  bottom: -20px;
  left: 0;
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}

.form-item:last-child {
  margin-bottom: 5px;
}

</style>